package com.learn.spring.observer.order;

import com.google.common.collect.Lists;
import com.learn.spring.observer.message.PlaceOrderMessage;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 被观察者抽象类
 *
 * @author cong zhi
 * @email 448341911@qq.com
 * @createDate 2023/3/20 16:40
 * @version: v1.0
 */
public abstract class OrderSubject {

    /**
     * 定义一个观察者列表
     */
    private List<OrderObserver> orderObserverList = Lists.newArrayList();

    /**
     * 定义一个线程池，这里参数随便写的
     */
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(6, 12, 6, TimeUnit.SECONDS, new ArrayBlockingQueue<>(30));

    /**
     * 增加一个观察者
     *
     * @param o
     */
    public void addObserver(OrderObserver o) {
        this.orderObserverList.add(o);
    }

    /**
     * 删除一个观察者
     *
     * @param o
     */
    public void delObserver(OrderObserver o) {
        this.orderObserverList.remove(o);
    }

    /**
     * 通知所有观察者
     * <p>这里利用了多线程，来异步执行观察者。</p>
     *
     * @param placeOrderMessage 消息体
     */
    public void notifyObserver(PlaceOrderMessage placeOrderMessage) {
        for (OrderObserver orderObserver : orderObserverList) {
            // 利用多线程异步执行
            threadPoolExecutor.execute(() -> {
                orderObserver.afterPlaceOrder(placeOrderMessage);
            });
        }

    }
}
